package com.smartbus.bus.service.impl;

import com.smartbus.bus.domain.TransferRoute;
import com.smartbus.bus.domain.TransferConfig;
import com.smartbus.bus.domain.BusStations;
import com.smartbus.bus.domain.BusRoutes;
import com.smartbus.bus.domain.RouteStations;
import com.smartbus.bus.domain.StationDistance;
import com.smartbus.bus.mapper.BusStationsMapper;
import com.smartbus.bus.mapper.BusRoutesMapper;
import com.smartbus.bus.mapper.RouteStationsMapper;
import com.smartbus.bus.mapper.StationDistanceMapper;
import com.smartbus.bus.service.TransferPathService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 换乘路径搜索服务实现类
 *
 * @author smartbus
 * @date 2024-09-24
 */
@Service
public class TransferPathServiceImpl implements TransferPathService {

    @Autowired
    private BusStationsMapper busStationsMapper;

    @Autowired
    private BusRoutesMapper busRoutesMapper;

    @Autowired
    private RouteStationsMapper routeStationsMapper;

    @Autowired
    private StationDistanceMapper stationDistanceMapper;

    /**
     * 搜索换乘路径
     */
    @Override
    public TransferRoute searchTransferRoute(Integer fromStationId, Integer toStationId, String mode) {
        long startTime = System.currentTimeMillis();

        // 获取换乘配置
        TransferConfig config = getTransferConfig(mode);

        // 获取起始和目标站点信息
        BusStations fromStation = busStationsMapper.selectBusStationsById(Long.valueOf(fromStationId));
        BusStations toStation = busStationsMapper.selectBusStationsById(Long.valueOf(toStationId));

        if (fromStation == null || toStation == null) {
            return null;
        }

        // 构建结果对象
        TransferRoute result = new TransferRoute(
            Long.valueOf(fromStationId), fromStation.getStationName(),
            Long.valueOf(toStationId), toStation.getStationName()
        );

        // 搜索换乘方案
        List<TransferRoute.TransferPlan> plans = searchTransferPlans(
            fromStationId, toStationId, config
        );

        result.setTransferPlans(plans);
        result.setQueryTime(System.currentTimeMillis() - startTime);

        return result;
    }

    /**
     * 重新计算站点间距离数据
     */
    @Override
    public int recalculateStationDistances() {
        return stationDistanceMapper.recalculateStationDistances();
    }

    /**
     * 检查换乘系统状态
     */
    @Override
    public String getTransferSystemStatus() {
        try {
            int totalStations = busStationsMapper.selectBusStationsList(new BusStations()).size();
            int totalRoutes = busRoutesMapper.selectBusRoutesList(new BusRoutes()).size();
            int totalDistances = stationDistanceMapper.selectStationDistanceList(new StationDistance()).size();
            int walkableDistances = stationDistanceMapper.selectWalkableDistances().size();

            return String.format("站点数: %d, 线路数: %d, 距离对: %d, 可步行换乘: %d",
                totalStations, totalRoutes, totalDistances, walkableDistances);
        } catch (Exception e) {
            return "系统状态检查失败: " + e.getMessage();
        }
    }

    /**
     * 搜索换乘方案（Dijkstra算法实现）
     */
    private List<TransferRoute.TransferPlan> searchTransferPlans(
            Integer fromStationId, Integer toStationId, TransferConfig config) {

        // 构建站点网络图
        Map<Integer, StationNode> stationNodes = buildStationGraph();

        // 运行Dijkstra算法
        List<PathResult> paths = dijkstraSearch(
            stationNodes, fromStationId, toStationId, config
        );

        // 转换为换乘方案
        List<TransferRoute.TransferPlan> plans = new ArrayList<>();
        for (int i = 0; i < paths.size() && i < config.getResultLimit(); i++) {
            PathResult path = paths.get(i);
            TransferRoute.TransferPlan plan = convertToTransferPlan(path, i + 1, fromStationId, toStationId);
            if (plan != null) {
                plans.add(plan);
            }
        }

        return plans;
    }

    /**
     * 构建站点网络图
     */
    private Map<Integer, StationNode> buildStationGraph() {
        Map<Integer, StationNode> nodes = new HashMap<>();

        // 获取所有站点
        List<BusStations> stations = busStationsMapper.selectBusStationsList(new BusStations());
        for (BusStations station : stations) {
            nodes.put(station.getId().intValue(), new StationNode(station.getId().intValue(), station.getStationName()));
        }

        // 添加线路连接
        addRouteConnections(nodes);

        // 添加步行换乘连接
        addWalkingConnections(nodes);

        return nodes;
    }

    /**
     * 添加线路连接
     */
    private void addRouteConnections(Map<Integer, StationNode> nodes) {
        // 获取所有线路
        List<BusRoutes> routes = busRoutesMapper.selectBusRoutesList(new BusRoutes());

        for (BusRoutes route : routes) {
            if (route.getIsActive() != 1) continue; // 只处理运营中的线路

            // 获取线路的所有站点，按顺序排列
            RouteStations queryParam = new RouteStations();
            queryParam.setRouteId(route.getId());
            List<RouteStations> routeStations = routeStationsMapper.selectRouteStationsList(queryParam);

            // 按站点顺序排序
            routeStations.sort(Comparator.comparing(RouteStations::getStationOrder));

            // 为相邻站点添加连接
            for (int i = 0; i < routeStations.size() - 1; i++) {
                RouteStations currentStation = routeStations.get(i);
                RouteStations nextStation = routeStations.get(i + 1);

                StationNode fromNode = nodes.get(currentStation.getStationId().intValue());
                StationNode toNode = nodes.get(nextStation.getStationId().intValue());

                if (fromNode != null && toNode != null) {
                    // 计算站点间距离和时间
                    BigDecimal distance = calculateDistance(currentStation, nextStation);
                    int time = calculateTime(currentStation, nextStation);

                    // 添加正向连接
                    fromNode.addConnection(new StationConnection(
                        nextStation.getStationId().intValue(),
                        route.getId().intValue(),
                        route.getRouteNumber(),
                        route.getRouteName(),
                        distance,
                        time,
                        0, // 0表示同线路连接，不需要换乘
                        BigDecimal.ZERO,
                        0
                    ));

                    // 如果是双向线路，添加反向连接（暂时假设都是双向）
                    toNode.addConnection(new StationConnection(
                        currentStation.getStationId().intValue(),
                        route.getId().intValue(),
                        route.getRouteNumber(),
                        route.getRouteName(),
                        distance,
                        time,
                        0,
                        BigDecimal.ZERO,
                        0
                    ));
                }
            }
        }
    }

    /**
     * 添加步行换乘连接
     */
    private void addWalkingConnections(Map<Integer, StationNode> nodes) {
        // 查询所有可步行换乘的站点对
        List<StationDistance> walkableDistances = stationDistanceMapper.selectWalkableDistances();

        for (StationDistance distance : walkableDistances) {
            StationNode fromNode = nodes.get(distance.getFromStationId());
            StationNode toNode = nodes.get(distance.getToStationId());

            if (fromNode != null && toNode != null) {
                // 添加步行换乘连接
                fromNode.addConnection(new StationConnection(
                    distance.getToStationId(),
                    null, // 步行换乘没有线路ID
                    "步行",
                    "步行换乘",
                    distance.getDistance(),
                    distance.getWalkingTime(),
                    2, // 2表示步行换乘
                    distance.getDistance(),
                    distance.getWalkingTime()
                ));
            }
        }
    }

    /**
     * Dijkstra算法搜索
     */
    private List<PathResult> dijkstraSearch(
            Map<Integer, StationNode> nodes, Integer fromStationId, Integer toStationId, TransferConfig config) {

        List<PathResult> allPaths = new ArrayList<>();

        // 搜索最短时间路径
        PathResult timePath = dijkstraSearchSingle(nodes, fromStationId, toStationId, config, "time");
        if (timePath != null) {
            timePath.setPlanType(2); // 最短时间
            allPaths.add(timePath);
        }

        // 搜索最少换乘路径
        PathResult transferPath = dijkstraSearchSingle(nodes, fromStationId, toStationId, config, "transfer");
        if (transferPath != null && !isDuplicatePath(transferPath, allPaths)) {
            transferPath.setPlanType(1); // 最少换乘
            allPaths.add(transferPath);
        }

        // 搜索最短距离路径
        PathResult distancePath = dijkstraSearchSingle(nodes, fromStationId, toStationId, config, "distance");
        if (distancePath != null && !isDuplicatePath(distancePath, allPaths)) {
            distancePath.setPlanType(3); // 最短距离
            allPaths.add(distancePath);
        }

        // 按推荐度排序
        allPaths.sort((a, b) -> Integer.compare(b.getRecommendScore(), a.getRecommendScore()));

        return allPaths;
    }

    /**
     * 单次Dijkstra搜索
     */
    private PathResult dijkstraSearchSingle(
            Map<Integer, StationNode> nodes, Integer fromStationId, Integer toStationId,
            TransferConfig config, String optimizeType) {

        // 初始化距离和前驱节点
        Map<Integer, Double> distances = new HashMap<>();
        Map<Integer, PathInfo> pathInfos = new HashMap<>();
        Set<Integer> visited = new HashSet<>();
        PriorityQueue<NodeDistance> queue = new PriorityQueue<>();

        // 初始化起点
        distances.put(fromStationId, 0.0);
        pathInfos.put(fromStationId, new PathInfo(null, null, 0, 0, BigDecimal.ZERO, 0));
        queue.offer(new NodeDistance(fromStationId, 0.0));

        long searchStartTime = System.currentTimeMillis();

        while (!queue.isEmpty()) {
            // 检查超时
            if (System.currentTimeMillis() - searchStartTime > config.getSearchTimeout()) {
                break;
            }

            NodeDistance current = queue.poll();
            Integer currentStationId = current.getStationId();

            if (visited.contains(currentStationId)) {
                continue;
            }

            visited.add(currentStationId);

            // 找到目标站点
            if (currentStationId.equals(toStationId)) {
                return buildPathResult(pathInfos, fromStationId, toStationId, nodes);
            }

            // 检查换乘次数限制
            PathInfo currentPath = pathInfos.get(currentStationId);
            if (currentPath.getTransferCount() >= config.getMaxTransferCount()) {
                continue;
            }

            // 遍历所有连接
            StationNode currentNode = nodes.get(currentStationId);
            if (currentNode == null) continue;

            for (StationConnection connection : currentNode.getConnections()) {
                Integer nextStationId = connection.getToStationId();

                if (visited.contains(nextStationId)) {
                    continue;
                }

                // 检查步行距离限制
                if (connection.getTransferType() == 2 &&
                    connection.getTransferWalkDistance().compareTo(config.getMaxWalkingDistance()) > 0) {
                    continue;
                }

                // 计算新的距离/时间/换乘次数
                double newCost = calculateCost(currentPath, connection, optimizeType, config);
                double currentCost = distances.getOrDefault(nextStationId, Double.MAX_VALUE);

                if (newCost < currentCost) {
                    distances.put(nextStationId, newCost);

                    // 更新路径信息
                    int newTransferCount = currentPath.getTransferCount();
                    if (connection.getTransferType() > 0 &&
                        (currentPath.getLastRouteId() == null || !currentPath.getLastRouteId().equals(connection.getRouteId()))) {
                        newTransferCount++;
                    }

                    pathInfos.put(nextStationId, new PathInfo(
                        currentStationId,
                        connection,
                        newTransferCount,
                        currentPath.getTotalTime() + connection.getTime(),
                        currentPath.getTotalDistance().add(connection.getDistance()),
                        currentPath.getTotalWalkTime() + connection.getTransferWalkTime()
                    ));

                    queue.offer(new NodeDistance(nextStationId, newCost));
                }
            }
        }

        return null; // 未找到路径
    }

    // 辅助方法和内部类...

    /**
     * 获取换乘配置
     */
    private TransferConfig getTransferConfig(String mode) {
        switch (mode) {
            case "fast":
                return TransferConfig.getFastMode();
            case "comfort":
                return TransferConfig.getComfortMode();
            default:
                return TransferConfig.getDefault();
        }
    }

    /**
     * 计算成本（根据优化类型）
     */
    private double calculateCost(PathInfo currentPath, StationConnection connection,
                                String optimizeType, TransferConfig config) {
        switch (optimizeType) {
            case "time":
                return currentPath.getTotalTime() + connection.getTime() +
                       (connection.getTransferType() > 0 ? config.getTransferWaitTime() : 0);
            case "transfer":
                int transferPenalty = 0;
                if (connection.getTransferType() > 0 &&
                    (currentPath.getLastRouteId() == null || !currentPath.getLastRouteId().equals(connection.getRouteId()))) {
                    transferPenalty = 1000; // 换乘惩罚
                }
                return currentPath.getTransferCount() * 1000 + transferPenalty + connection.getTime();
            case "distance":
                return currentPath.getTotalDistance().add(connection.getDistance()).doubleValue();
            default:
                return currentPath.getTotalTime() + connection.getTime();
        }
    }

    // 计算站点间距离
    private BigDecimal calculateDistance(RouteStations current, RouteStations next) {
        if (next.getDistanceFromStart() != null && current.getDistanceFromStart() != null) {
            return next.getDistanceFromStart().subtract(current.getDistanceFromStart());
        }
        return new BigDecimal("2.0"); // 默认2公里
    }

    // 计算站点间时间
    private int calculateTime(RouteStations current, RouteStations next) {
        if (next.getEstimatedArrivalTime() != null && current.getEstimatedArrivalTime() != null) {
            return (int) (next.getEstimatedArrivalTime() - current.getEstimatedArrivalTime());
        }
        return 3; // 默认3分钟
    }

    // 内部辅助类定义...

    /**
     * 站点节点类
     */
    public static class StationNode {
        private Integer stationId;
        private String stationName;
        private List<StationConnection> connections;

        public StationNode(Integer stationId, String stationName) {
            this.stationId = stationId;
            this.stationName = stationName;
            this.connections = new ArrayList<>();
        }

        public void addConnection(StationConnection connection) {
            this.connections.add(connection);
        }

        // Getters and Setters
        public Integer getStationId() { return stationId; }
        public String getStationName() { return stationName; }
        public List<StationConnection> getConnections() { return connections; }
    }

    /**
     * 站点连接类
     */
    public static class StationConnection {
        private Integer toStationId;
        private Integer routeId;
        private String routeCode;
        private String routeName;
        private BigDecimal distance;
        private Integer time;
        private Integer transferType; // 0-同线路，1-同站换乘，2-步行换乘
        private BigDecimal transferWalkDistance;
        private Integer transferWalkTime;

        public StationConnection(Integer toStationId, Integer routeId, String routeCode, String routeName,
                               BigDecimal distance, Integer time, Integer transferType,
                               BigDecimal transferWalkDistance, Integer transferWalkTime) {
            this.toStationId = toStationId;
            this.routeId = routeId;
            this.routeCode = routeCode;
            this.routeName = routeName;
            this.distance = distance;
            this.time = time;
            this.transferType = transferType;
            this.transferWalkDistance = transferWalkDistance;
            this.transferWalkTime = transferWalkTime;
        }

        // Getters
        public Integer getToStationId() { return toStationId; }
        public Integer getRouteId() { return routeId; }
        public String getRouteCode() { return routeCode; }
        public String getRouteName() { return routeName; }
        public BigDecimal getDistance() { return distance; }
        public Integer getTime() { return time; }
        public Integer getTransferType() { return transferType; }
        public BigDecimal getTransferWalkDistance() { return transferWalkDistance; }
        public Integer getTransferWalkTime() { return transferWalkTime; }
    }

    /**
     * 路径结果类
     */
    public static class PathResult {
        private List<StationConnection> path;
        private Integer transferCount;
        private BigDecimal totalDistance;
        private Integer totalTime;
        private Integer totalWalkTime;
        private Integer recommendScore;
        private Integer planType;

        public PathResult() {
            this.path = new ArrayList<>();
        }

        // Getters and Setters
        public List<StationConnection> getPath() { return path; }
        public void setPath(List<StationConnection> path) { this.path = path; }
        public Integer getTransferCount() { return transferCount; }
        public void setTransferCount(Integer transferCount) { this.transferCount = transferCount; }
        public BigDecimal getTotalDistance() { return totalDistance; }
        public void setTotalDistance(BigDecimal totalDistance) { this.totalDistance = totalDistance; }
        public Integer getTotalTime() { return totalTime; }
        public void setTotalTime(Integer totalTime) { this.totalTime = totalTime; }
        public Integer getTotalWalkTime() { return totalWalkTime; }
        public void setTotalWalkTime(Integer totalWalkTime) { this.totalWalkTime = totalWalkTime; }
        public Integer getRecommendScore() { return recommendScore; }
        public void setRecommendScore(Integer recommendScore) { this.recommendScore = recommendScore; }
        public Integer getPlanType() { return planType; }
        public void setPlanType(Integer planType) { this.planType = planType; }
    }

    /**
     * 路径信息类
     */
    public static class PathInfo {
        private Integer previousStationId;
        private StationConnection lastConnection;
        private Integer transferCount;
        private Integer totalTime;
        private BigDecimal totalDistance;
        private Integer totalWalkTime;

        public PathInfo(Integer previousStationId, StationConnection lastConnection,
                       Integer transferCount, Integer totalTime,
                       BigDecimal totalDistance, Integer totalWalkTime) {
            this.previousStationId = previousStationId;
            this.lastConnection = lastConnection;
            this.transferCount = transferCount;
            this.totalTime = totalTime;
            this.totalDistance = totalDistance;
            this.totalWalkTime = totalWalkTime;
        }

        public Integer getLastRouteId() {
            return lastConnection != null ? lastConnection.getRouteId() : null;
        }

        // Getters
        public Integer getPreviousStationId() { return previousStationId; }
        public StationConnection getLastConnection() { return lastConnection; }
        public Integer getTransferCount() { return transferCount; }
        public Integer getTotalTime() { return totalTime; }
        public BigDecimal getTotalDistance() { return totalDistance; }
        public Integer getTotalWalkTime() { return totalWalkTime; }
    }

    /**
     * 节点距离类（优先队列使用）
     */
    public static class NodeDistance implements Comparable<NodeDistance> {
        private Integer stationId;
        private Double distance;

        public NodeDistance(Integer stationId, Double distance) {
            this.stationId = stationId;
            this.distance = distance;
        }

        @Override
        public int compareTo(NodeDistance other) {
            return Double.compare(this.distance, other.distance);
        }

        public Integer getStationId() { return stationId; }
        public Double getDistance() { return distance; }
    }

    /**
     * 构建路径结果
     */
    private PathResult buildPathResult(Map<Integer, PathInfo> pathInfos, Integer fromStationId, Integer toStationId,
                                     Map<Integer, StationNode> nodes) {
        PathResult result = new PathResult();
        List<StationConnection> path = new ArrayList<>();

        // 回溯路径
        Integer currentStationId = toStationId;
        while (currentStationId != null && !currentStationId.equals(fromStationId)) {
            PathInfo pathInfo = pathInfos.get(currentStationId);
            if (pathInfo == null || pathInfo.getLastConnection() == null) {
                break;
            }
            path.add(0, pathInfo.getLastConnection());
            currentStationId = pathInfo.getPreviousStationId();
        }

        result.setPath(path);

        // 计算统计信息
        BigDecimal totalDistance = BigDecimal.ZERO;
        int totalTime = 0;
        int totalWalkTime = 0;
        int transferCount = 0;
        Integer lastRouteId = null;

        for (StationConnection connection : path) {
            totalDistance = totalDistance.add(connection.getDistance());
            totalTime += connection.getTime();
            totalWalkTime += connection.getTransferWalkTime();

            if (connection.getTransferType() > 0 &&
                (lastRouteId == null || !lastRouteId.equals(connection.getRouteId()))) {
                transferCount++;
            }
            lastRouteId = connection.getRouteId();
        }

        result.setTotalDistance(totalDistance);
        result.setTotalTime(totalTime);
        result.setTotalWalkTime(totalWalkTime);
        result.setTransferCount(Math.max(0, transferCount - 1)); // 减去起始段

        // 计算推荐度评分
        result.setRecommendScore(calculateRecommendScore(result));

        return result;
    }

    /**
     * 计算推荐度评分
     */
    private int calculateRecommendScore(PathResult pathResult) {
        int score = 100;

        // 换乘次数惩罚：每次换乘扣20分
        score -= pathResult.getTransferCount() * 20;

        // 时间惩罚：超过60分钟每10分钟扣5分
        if (pathResult.getTotalTime() > 60) {
            score -= ((pathResult.getTotalTime() - 60) / 10) * 5;
        }

        // 步行时间惩罚：超过10分钟每分钟扣2分
        if (pathResult.getTotalWalkTime() > 10) {
            score -= (pathResult.getTotalWalkTime() - 10) * 2;
        }

        // 距离奖励：距离越短分数越高（适度）
        if (pathResult.getTotalDistance().compareTo(new BigDecimal("10")) <= 0) {
            score += 5;
        }

        return Math.max(10, Math.min(100, score));
    }

    /**
     * 转换为换乘方案
     */
    private TransferRoute.TransferPlan convertToTransferPlan(PathResult pathResult, int planId, Integer fromStationId, Integer toStationId) {
        TransferRoute.TransferPlan plan = new TransferRoute.TransferPlan();

        plan.setPlanId(planId);
        plan.setTransferCount(pathResult.getTransferCount());
        plan.setTotalDistance(pathResult.getTotalDistance());
        plan.setTotalTime(pathResult.getTotalTime());
        plan.setWalkingTime(pathResult.getTotalWalkTime());
        plan.setRecommendScore(pathResult.getRecommendScore());
        plan.setPlanType(pathResult.getPlanType());

        // 计算步行距离
        BigDecimal walkingDistance = pathResult.getPath().stream()
            .map(StationConnection::getTransferWalkDistance)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        plan.setWalkingDistance(walkingDistance);

        // 构建线路段
        List<TransferRoute.RouteSegment> segments = buildRouteSegments(pathResult.getPath(), fromStationId, toStationId);
        plan.setRouteSegments(segments);

        return plan;
    }

    /**
     * 构建线路段
     */
    private List<TransferRoute.RouteSegment> buildRouteSegments(List<StationConnection> path, Integer startStationId, Integer endStationId) {
        List<TransferRoute.RouteSegment> segments = new ArrayList<>();

        if (path.isEmpty()) {
            return segments;
        }

        int segmentOrder = 1;
        Integer currentRouteId = null;
        Integer segmentStartStationId = startStationId; // 使用传入的起始站点
        Integer previousStationId = startStationId;
        BigDecimal segmentDistance = BigDecimal.ZERO;
        int segmentTime = 0;
        int stationCount = 0;

        for (int i = 0; i < path.size(); i++) {
            StationConnection connection = path.get(i);

            // 如果是新线路段开始
            if (!Objects.equals(connection.getRouteId(), currentRouteId)) {
                // 结束前一个线路段
                if (currentRouteId != null && segmentStartStationId != null && previousStationId != null) {
                    TransferRoute.RouteSegment segment = createRouteSegment(
                        segmentOrder++, currentRouteId, segmentStartStationId, previousStationId,
                        segmentDistance, segmentTime, stationCount, path
                    );
                    segments.add(segment);
                }

                // 开始新线路段
                currentRouteId = connection.getRouteId();
                segmentStartStationId = previousStationId; // 前一段的终点成为新段的起点

                segmentDistance = BigDecimal.ZERO;
                segmentTime = 0;
                stationCount = 0;
            }

            // 累加当前连接的信息
            segmentDistance = segmentDistance.add(connection.getDistance());
            segmentTime += connection.getTime();
            stationCount++;
            previousStationId = connection.getToStationId();
        }

        // 处理最后一个线路段
        if (currentRouteId != null && segmentStartStationId != null && previousStationId != null) {
            TransferRoute.RouteSegment segment = createRouteSegment(
                segmentOrder, currentRouteId, segmentStartStationId, previousStationId,
                segmentDistance, segmentTime, stationCount, path
            );
            segments.add(segment);
        }

        return segments;
    }

    /**
     * 创建线路段对象
     */
    private TransferRoute.RouteSegment createRouteSegment(
            int segmentOrder, Integer routeId, Integer boardStationId, Integer alightStationId,
            BigDecimal segmentDistance, int segmentTime, int stationCount,
            List<StationConnection> path) {

        TransferRoute.RouteSegment segment = new TransferRoute.RouteSegment();
        segment.setSegmentOrder(segmentOrder);

        if (routeId != null) {
            segment.setRouteId(Long.valueOf(routeId));
        }

        if (boardStationId != null) {
            segment.setBoardStationId(Long.valueOf(boardStationId));
            // 获取上车站点名称
            segment.setBoardStationName(getStationNameById(boardStationId));
        }

        if (alightStationId != null) {
            segment.setAlightStationId(Long.valueOf(alightStationId));
            // 获取下车站点名称
            segment.setAlightStationName(getStationNameById(alightStationId));
        }

        segment.setRouteCode(getRouteCodeFromPath(path, routeId));
        segment.setRouteName(getRouteNameFromPath(path, routeId));
        segment.setSegmentDistance(segmentDistance);
        segment.setSegmentTime(segmentTime);
        segment.setStationCount(stationCount);

        return segment;
    }

    /**
     * 根据站点ID获取站点名称
     */
    private String getStationNameById(Integer stationId) {
        try {
            if (stationId != null) {
                BusStations station = busStationsMapper.selectBusStationsById(Long.valueOf(stationId));
                return station != null ? station.getStationName() : "未知站点";
            }
        } catch (Exception e) {
            System.out.println("获取站点名称失败: stationId=" + stationId + ", error=" + e.getMessage());
        }
        return "未知站点";
    }

    /**
     * 从路径中获取线路编号
     */
    private String getRouteCodeFromPath(List<StationConnection> path, Integer routeId) {
        for (StationConnection connection : path) {
            if (Objects.equals(connection.getRouteId(), routeId)) {
                return connection.getRouteCode();
            }
        }
        return null;
    }

    /**
     * 从路径中获取线路名称
     */
    private String getRouteNameFromPath(List<StationConnection> path, Integer routeId) {
        for (StationConnection connection : path) {
            if (Objects.equals(connection.getRouteId(), routeId)) {
                return connection.getRouteName();
            }
        }
        return null;
    }

    /**
     * 判断是否为重复路径
     */
    private boolean isDuplicatePath(PathResult newPath, List<PathResult> existingPaths) {
        for (PathResult existing : existingPaths) {
            if (isSimilarPath(newPath, existing)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断路径是否相似
     */
    private boolean isSimilarPath(PathResult path1, PathResult path2) {
        // 简单的相似性判断：换乘次数相同且时间差在10分钟内
        return path1.getTransferCount().equals(path2.getTransferCount()) &&
               Math.abs(path1.getTotalTime() - path2.getTotalTime()) <= 10;
    }
}
